<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { message } from "@/utils/message";
import type { FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import Motion from "../utils/motion";

import Lock from "~icons/ri/lock-fill";
import Email from "~icons/ri/mail-fill";

defineOptions({
  name: "EmailLogin"
});

const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(["update:loading"]);

const emailFormRef = ref<FormInstance>();

// 邮箱验证码登录表单
const emailForm = reactive({
  email: "",
  code: ""
});

// 验证码相关
const codeSending = ref(false);
const countdown = ref(0);
const countdownTimer = ref<number | null>(null);

// 发送验证码
const sendVerificationCode = async () => {
  if (!emailForm.email) {
    message("请输入邮箱地址", { type: "warning" });
    return;
  }

  codeSending.value = true;
  try {
    // 这里应该是调用发送验证码的API
    // await sendCodeAPI(emailForm.email);

    message("验证码已发送", { type: "success" });
    countdown.value = 60;

    // 开始倒计时
    countdownTimer.value = window.setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer.value as number);
        countdownTimer.value = null;
      }
    }, 1000);
  } catch (error) {
    message("验证码发送失败", { type: "error" });
  } finally {
    codeSending.value = false;
  }
};

// 邮箱验证码登录（UI演示，不实际调用API）
const onEmailLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      emit("update:loading", true);

      // 模拟登录过程
      setTimeout(() => {
        message("邮箱登录功能仅作UI展示", { type: "info" });
        emit("update:loading", false);
      }, 1000);
    }
  });
};

defineExpose({
  emailFormRef,
  onEmailLogin
});
</script>

<template>
  <el-form ref="emailFormRef" :model="emailForm" size="large">
    <Motion :delay="100">
      <el-form-item
        prop="email"
        :rules="[
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '请输入正确的邮箱格式',
            trigger: 'blur'
          }
        ]"
      >
        <el-input
          v-model="emailForm.email"
          clearable
          placeholder="邮箱"
          :prefix-icon="useRenderIcon(Email)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="150">
      <el-form-item
        prop="code"
        :rules="[
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }
        ]"
      >
        <div class="flex items-center space-x-2 p-0 m-0">
          <el-input
            v-model="emailForm.code"
            clearable
            placeholder="验证码"
            :prefix-icon="useRenderIcon(Lock)"
          />
          <el-button
            :disabled="codeSending || countdown > 0"
            type="primary"
            style="margin-bottom: 8px"
            @click="sendVerificationCode"
          >
            {{ countdown > 0 ? `${countdown}秒后重试` : "获取验证码" }}
          </el-button>
        </div>
      </el-form-item>
    </Motion>

    <Motion :delay="250">
      <el-button
        class="login-button"
        size="large"
        type="primary"
        :loading="loading"
        :disabled="disabled"
        @click="onEmailLogin(emailFormRef)"
      >
        登录
      </el-button>
    </Motion>
  </el-form>
</template>

<style lang="scss" scoped>
.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
  border-radius: 6px;
}
</style>
